import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/3/18
 * \* Time: 11:00
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class Add {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        //1.创建数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");
        //2.让代码与数据库建立连接
        Connection connection = dataSource.getConnection();
        //2.5 让用户通过控制台输入一下待插入的数据
        System.out.println("请输入学号：");
        int id = scanner.nextInt();
        System.out.println("请输入姓名：");
        String name = scanner.next();
        //3.操作数据库，以插入数据为例
        String sql = "insert into student values(?, ?)";//用?代表不确定
        PreparedStatement statement = connection.prepareStatement(sql);
        //进行替换操作
        statement.setInt(1, id);
        statement.setString(2, name);
        System.out.println("statement:" + statement);

        //4.执行SQL
        int ret = statement.executeUpdate();
        System.out.println(ret);
        //5.此时SQL已经执行完毕，然后还需要释放资源
        statement.close();
        connection.close();
    }
}

